package moveresize;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;

public class BoundsHistory {
	private final Control control;
    private AtomicBoolean attached;
	
	public BoundsHistory(Control control) {
		this.control = control;
        attached = new AtomicBoolean(false);
	}
	
	private ControlListener controlListener = new ControlListener() {

		public void controlMoved(ControlEvent e) {
			if (!Resizer.isResizing(control)) {
				pushBounds(control.getBounds());
			}
		}

		public void controlResized(ControlEvent e) {
			if (!Resizer.isResizing(control)) {
				pushBounds(control.getBounds());
			}
		}
		
	};
	private KeyListener keyListener = new KeyListener() {

		public void keyPressed(KeyEvent e) {
			Control control = getControl();

			if (control.isDisposed()) {
				return;
			}
			
			if (e.character == 'z') {
				try {
		        	control.removeControlListener(controlListener);
					backward();
				} finally {
		        	control.addControlListener(controlListener);
				}
			} else if (e.character == 'y') {
				try {
		        	control.removeControlListener(controlListener);
					forward();
				} finally {
		        	control.addControlListener(controlListener);
				}
			}
		}

		public void keyReleased(KeyEvent e) {
		}
		
	};
	
	public Control getControl() {
		return control;
	}
	
	public void attach() {
        if (attached.compareAndSet(false, true)) {
        	control.addControlListener(controlListener);
    		control.addKeyListener(keyListener);
    		pushBounds(control.getBounds());
        }
	}

	public void deattach() {
        if (attached.compareAndSet(true, false)) {
        	control.removeControlListener(controlListener);
        	control.removeKeyListener(keyListener);
        }
	}
	
	private List<Rectangle> boundsHistory = new LinkedList<Rectangle>();
	private int historyIndex = -1;
	
	private void pushBounds(Rectangle bounds) {
		if (historyIndex >= 0) {
			while (historyIndex < boundsHistory.size() - 1) {
				boundsHistory.remove(boundsHistory.size() - 1);
			}
		}
		boundsHistory.add(bounds);
		historyIndex = boundsHistory.size() -1;
	}

	private void backward() {
		if (historyIndex <= 0) {
			return;
		}
		historyIndex--;
		Rectangle bounds = boundsHistory.get(historyIndex);
		control.setBounds(bounds);
	}
	
	private void forward() {
		if (historyIndex >= (boundsHistory.size() -1)) {
			return;
		}
		historyIndex++;
		Rectangle bounds = boundsHistory.get(historyIndex);
		control.setBounds(bounds);
	}

}
